﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace Marbles.Core.Filters
{
    public class WhiteSpaceResponseFilter : HttpResponseFilter
    {
        private StringBuilder responseHtml = null;

        public WhiteSpaceResponseFilter(Stream output)
            : base(output)
        {
            responseHtml = new StringBuilder();
        }


        public override void Write(byte[] buffer, int offset, int count)
        {
            string strHtml = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count);
            Regex eof = new Regex("</html>", RegexOptions.IgnoreCase);

            if (!eof.IsMatch(strHtml))
            {
                responseHtml.Append(strHtml);
            }
            else
            {
                responseHtml.Append(strHtml);
                byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(ReplaceWhiteSpace(responseHtml));
                BaseStream.Write(data, 0, data.Length);
            }

        }

        internal static string ReplaceWhiteSpace(StringBuilder responseHtml)
        {
            return Regex.Replace(responseHtml.ToString(), "<![CDATA[(?<=[^]\\t{2,}|(?<=[>])\\s{2,}(?=[<])|(?<=[>])\\s{2,11}(?=[<])|(?=[\\n])\\s{2,}]]>", "");
        }

        public override void Close()
        {
            base.Close();
        }

        public override void Flush()
        {
            base.Flush();
        }
    }
}